<template>
  <el-dialog
    :title="editMode ? '编辑模板' : '新增模板'"
    :visible.sync="dialogVisible"
    width="80%"
    @close="handleDialogClose"
  >
    <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="模板名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入模板名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="超时阈值(秒)" prop="sqlTimeoutThreshold">
            <el-input-number
              v-model="form.sqlTimeoutThresholdSeconds"
              :min="1"
              :max="3600"
              :step="1"
              @change="form.sqlTimeoutThreshold = $event * 1000"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="2"
          placeholder="请输入模板描述"
        />
      </el-form-item>
      <el-form-item label="线程匹配策略" prop="threadMatchingStrategy">
        <el-select v-model="form.threadMatchingStrategy">
          <el-option label="精确匹配" value="exact" />
          <el-option label="前缀匹配" value="prefix" />
          <el-option label="包含匹配" value="contains" />
        </el-select>
      </el-form-item>
      <el-divider content-position="left">模板定义</el-divider>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="Preparing模板" prop="preparingFormat">
            <el-input
              v-model="form.preparingFormat"
              type="textarea"
              :rows="3"
              placeholder="如: {time} [{thread}] {level} {class} - ==>  Preparing: {sql} 或 {time} [{thread}] {level} {class}: {msg}"
            />
            <el-button
              size="mini"
              type="primary"
              @click="generateRegex('preparing')"
              style="margin-top: 5px"
              >生成正则</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="Parameters模板" prop="parametersFormat">
            <el-input
              v-model="form.parametersFormat"
              type="textarea"
              :rows="3"
              placeholder="如: {time} [{thread}] {level} {class} - ==> Parameters: {params} 或 {time} [{thread}] {level} {class}: {msg}"
            />
            <el-button
              size="mini"
              type="primary"
              @click="generateRegex('parameters')"
              style="margin-top: 5px"
              >生成正则</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="Total模板" prop="totalFormat">
            <el-input
              v-model="form.totalFormat"
              type="textarea"
              :rows="3"
              placeholder="如: {time} [{thread}] {level} {class} - <==      Total: {total} 或 {time} [{thread}] {level} {class}: {msg}"
            />
            <el-button
              size="mini"
              type="primary"
              @click="generateRegex('total')"
              style="margin-top: 5px"
              >生成正则</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">正则表达式</el-divider>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="Preparing正则">
            <el-input
              v-model="form.preparingRegex"
              type="textarea"
              :rows="3"
              placeholder="请输入或自动生成正则表达式"
            />
            <div style="margin-top: 5px">
              <el-button size="mini" @click="generateRegex('preparing')"
                >自动生成</el-button
              >
              <span style="color: #999; font-size: 12px; margin-left: 8px">
                如自动生成不准确，请手动修改正则表达式。
              </span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="Parameters正则">
            <el-input
              v-model="form.parametersRegex"
              type="textarea"
              :rows="3"
              placeholder="请输入或自动生成正则表达式"
            />
            <div style="margin-top: 5px">
              <el-button size="mini" @click="generateRegex('parameters')"
                >自动生成</el-button
              >
              <span style="color: #999; font-size: 12px; margin-left: 8px">
                如自动生成不准确，请手动修改正则表达式。
              </span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="Total正则">
            <el-input
              v-model="form.totalRegex"
              type="textarea"
              :rows="3"
              placeholder="请输入或自动生成正则表达式"
            />
            <div style="margin-top: 5px">
              <el-button size="mini" @click="generateRegex('total')"
                >自动生成</el-button
              >
              <span style="color: #999; font-size: 12px; margin-left: 8px">
                如自动生成不准确，请手动修改正则表达式。
              </span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">正则测试</el-divider>
      <el-form-item label="测试日志">
        <el-input
          v-model="testLogText"
          type="textarea"
          :rows="4"
          placeholder="输入日志文本进行正则测试"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="testRegex('preparing')" type="primary"
          >测试Preparing</el-button
        >
        <el-button @click="testRegex('parameters')" type="primary"
          >测试Parameters</el-button
        >
        <el-button @click="testRegex('total')" type="primary"
          >测试Total</el-button
        >
      </el-form-item>
      <el-form-item v-if="testResult" label="测试结果">
        <el-alert
          :title="testResult.success ? '匹配成功' : '匹配失败'"
          :type="testResult.success ? 'success' : 'error'"
          :description="testResult.message"
          show-icon
        />
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="onSave">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "TemplateEditDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    editMode: {
      type: Boolean,
      default: false,
    },
    template: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      form: {
        name: "",
        description: "",
        sqlTimeoutThreshold: 30000,
        sqlTimeoutThresholdSeconds: 30,
        threadMatchingStrategy: "exact",
        preparingFormat: "",
        parametersFormat: "",
        totalFormat: "",
        preparingRegex: "",
        parametersRegex: "",
        totalRegex: "",
        enabled: true,
      },
      testLogText: "",
      testResult: null,
      rules: {
        name: [{ required: true, message: "请输入模板名称", trigger: "blur" }],
        description: [
          { required: true, message: "请输入模板描述", trigger: "blur" },
        ],
        threadMatchingStrategy: [
          { required: true, message: "请选择线程匹配策略", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
  },
  watch: {
    template: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.form = {
            ...newVal,
            sqlTimeoutThresholdSeconds:
              (newVal.sqlTimeoutThreshold || 30000) / 1000,
          };
        } else {
          this.resetForm();
        }
      },
      immediate: true,
    },
    visible(newVal) {
      if (!newVal) {
        this.resetForm();
      }
    },
  },
  methods: {
    resetForm() {
      this.form = {
        name: "",
        description: "",
        sqlTimeoutThreshold: 30000,
        sqlTimeoutThresholdSeconds: 30,
        threadMatchingStrategy: "exact",
        preparingFormat: "",
        parametersFormat: "",
        totalFormat: "",
        preparingRegex: "",
        parametersRegex: "",
        totalRegex: "",
        enabled: true,
      };
      this.testLogText = "";
      this.testResult = null;
    },
    handleDialogClose() {
      this.resetForm();
    },
    generateRegex(type) {
      const format = this.form[`${type}Format`];
      if (!format) {
        this.$message.warning("请先输入模板格式");
        return;
      }

      const regex = this.templateToRegex(format, type);
      this.form[`${type}Regex`] = regex;
      this.$message.success(`${type}正则表达式已生成`);
    },
    templateToRegex(template, type) {
      // 先转义特殊字符，但保留占位符
      let regex = template
        .replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
      
      // 然后替换占位符为命名捕获组
      regex = regex
        .replace(/\\\{time\\\}/g, "(?<time>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(?::\\d{3}|\\.\\d{3})?)")
        .replace(/\\\{thread\\\}/g, "(?<thread>[^\\]]+)")
        .replace(/\\\{level\\\}/g, "(?<level>\\w+)")
        .replace(/\\\{class\\\}/g, "(?<class>[\\w\\.]+)")
        .replace(/\\\{msg\\\}/g, "(?<msg>.+)");

      if (type === "preparing") {
        regex = regex.replace(/\\\{sql\\\}/g, "(?<sql>.+)");
      } else if (type === "parameters") {
        regex = regex.replace(/\\\{params\\\}/g, "(?<params>.+)");
      } else if (type === "total") {
        regex = regex.replace(/\\\{total\\\}/g, "(?<total>\\d+)");
      }

      return regex;
    },
    testRegex(type) {
      const regexStr = this.form[`${type}Regex`];
      if (!regexStr) {
        this.$message.warning("请先生成正则表达式");
        return;
      }

      if (!this.testLogText) {
        this.$message.warning("请输入测试日志");
        return;
      }

      try {
        const regex = new RegExp(regexStr);
        const match = this.testLogText.match(regex);

        if (match) {
          this.testResult = {
            success: true,
            message: "正则表达式匹配成功",
            groups: match.groups || {},
          };
        } else {
          this.testResult = {
            success: false,
            message: "正则表达式匹配失败",
          };
        }
      } catch (error) {
        this.testResult = {
          success: false,
          message: `正则表达式错误: ${error.message}`,
        };
      }
    },
    async onSave() {
      try {
        await this.$refs.formRef.validate();

        const templateData = {
          ...this.form,
          sqlTimeoutThreshold: this.form.sqlTimeoutThresholdSeconds * 1000,
        };

        delete templateData.sqlTimeoutThresholdSeconds;

        const url = this.editMode
          ? `http://localhost:8080/api/template/${
              this.template && this.template.id
            }`
          : "http://localhost:8080/api/template";

        const method = this.editMode ? "put" : "post";

        await this.$axios[method](url, templateData);

        this.$message.success(this.editMode ? "模板更新成功" : "模板创建成功");
        this.$emit("refresh");
        this.$emit("update:visible", false);
      } catch (error) {
        if (error.message) {
          this.$message.error(error.message);
        }
      }
    },
    handleCancel() {
      this.resetForm();
      this.$emit("close");
      this.$emit("update:visible", false);
    },
  },
};
</script> 